using System;
using System.IO;
using System.Text;

namespace HtERP.Services
{
    /// <summary>
    /// 文件日志记录器
    /// </summary>
    public class FileLogger : ILogger
    {
        private readonly string _logFilePath;
        private LogLevel _minLogLevel = LogLevel.Info;
        private readonly object _lock = new object();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logFilePath">日志文件路径</param>
        /// <param name="level">日志级别</param>
        public FileLogger(string logFilePath, LogLevel level = LogLevel.Info)
        {
            _logFilePath = logFilePath;
            _minLogLevel = level;

            // 确保日志目录存在
            string logDirectory = Path.GetDirectoryName(logFilePath);
            if (!string.IsNullOrEmpty(logDirectory) && !Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        public void Log(LogLevel level, string message)
        {
            if (level < _minLogLevel)
                return;

            string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
            WriteToFile(logEntry);
        }

        /// <summary>
        /// 记录日志（带异常信息）
        /// </summary>
        public void Log(LogLevel level, string message, Exception ex)
        {
            if (level < _minLogLevel)
                return;

            string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
            if (ex != null)
            {
                logEntry += Environment.NewLine + $"  Exception: {ex.Message}";
                logEntry += Environment.NewLine + $"  StackTrace: {ex.StackTrace}";
            }
            WriteToFile(logEntry);
        }

        /// <summary>
        /// 设置日志级别
        /// </summary>
        public void SetLogLevel(LogLevel level)
        {
            _minLogLevel = level;
        }

        /// <summary>
        /// 写入日志到文件
        /// </summary>
        private void WriteToFile(string logEntry)
        {
            try
            {
                lock (_lock)
                {
                    using (StreamWriter writer = new StreamWriter(_logFilePath, true, Encoding.UTF8))
                    {
                        writer.WriteLine(logEntry);
                    }
                }
            }
            catch (Exception)
            {
                // 如果写入日志失败，忽略异常
            }
        }
    }
}